﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using WeiBeeCommon.DataTypes;

namespace WeiBeeCommon.Core
{
    public class AuthEntity : IComparable<AuthEntity>
    {
        public string ConsumerKey { set; get; }
        public string ConsumerSecret { set; get; }
        public string Token {set; get;}
        public string TokenSecret { set; get; }
        public DateTime ActTime { set; get; }
        [XmlElement("UserType")]
        public WeiBeeType UserType { set; get; }
        [XmlChoiceIdentifier("UserType")]
        [XmlElement("Sina",typeof(SinaUser))]
        [XmlElement("Sohu",typeof(SohuUser))]        
        public UserBase user { set; get; }
        [XmlIgnore]
        public string DisplayName
        {
            get
            {
                string result = string.Empty;
                if (user != null)
                {
                    if (user is SinaUser)
                    {
                        result = user.name;
                    }
                    else if (user is SohuUser)
                    {
                        result = (user as SohuUser).ScreenName;
                    }
                }
                return result;
            }
        }
        public IWeiBee GetWeiBee()
        {
            var result = WeiBeeFactory.CreateWeiBeeByType(UserType==WeiBeeType.None?WeiBeeType.Sina:UserType);
            result.GetOAuth().ConsumerKey = ConsumerKey;
            result.GetOAuth().ConsumerSecret = ConsumerSecret;
            result.SetOAuth(Token, TokenSecret);
            return result;
        }
        public WeiBeeSina GetWeiBeeSina()
        {
            var result = new WeiBeeSina();
            result.OAuth.ConsumerKey = ConsumerKey;
            result.OAuth.ConsumerSecret = ConsumerSecret;
            result.OAuth.Token = Token;
            result.OAuth.TokenSecret = TokenSecret;
            return result;
        }
        public int CompareTo(AuthEntity other)
        {
            return DateTime.Compare(this.ActTime, other.ActTime);
        }
    }
    public class AuthEntityComparer : IEqualityComparer<AuthEntity>
    {
        public bool Equals(AuthEntity x, AuthEntity y)
        {
            return x.Token == y.Token;
        }

        public int GetHashCode(AuthEntity obj)
        {
            int result;
            if (!int.TryParse(obj.user.id, out result))
            {
                result = int.Parse(obj.user.id.Substring(0,int.MaxValue.ToString().Length-1));
            }
            return result;
        }
    }
    
    public class EntityHelper
    {
        public string entityfile = "authentity.xml";
        public List<AuthEntity> LoadEntities()
        {
            var result = new List<AuthEntity>();
            if (File.Exists(entityfile))
            {
                using (FileStream fs = new FileStream(entityfile, FileMode.Open, FileAccess.Read))
                {
                    XmlRootAttribute root = new XmlRootAttribute("Entities");
                    var ser = new XmlSerializer(typeof(List<AuthEntity>), root);
                    result = ser.Deserialize(fs) as List<AuthEntity>;
                }
            }
            return result;
        }
        public void SaveEntities(List<AuthEntity> entities)
        {
            using (FileStream fs = new FileStream(entityfile, FileMode.Create, FileAccess.Write))
            {
                XmlRootAttribute root = new XmlRootAttribute("Entities");
                var ser = new XmlSerializer(typeof(List<AuthEntity>), root);
                ser.Serialize(fs, entities);
            }
        }

        /// <summary>
        /// 从文件载入被@的用户列表
        /// </summary>
        /// <param name="atfile">文件名，默认为"atusers.xml"</param>
        /// <returns>待@的用户列表</returns>
        public List<string> LoadAts(string atfile = "atusers.xml")
        {
            var result = new List<string>();
            if (File.Exists(atfile))
            {
                using (StreamReader sr = new StreamReader(atfile))
                {
                    XmlRootAttribute root = new XmlRootAttribute("AtUsers");
                    var ser = new XmlSerializer(typeof(List<string>), root);
                    try
                    {
                        result = ser.Deserialize(sr) as List<string>;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                }
            }
            return result;
        }

        public void SaveAts(List<string> atusers, string atfile = "atusers.xml")
        {
            using (StreamWriter sw = new StreamWriter(atfile))
            {
                XmlRootAttribute root = new XmlRootAttribute("AtUsers");
                var ser = new XmlSerializer(typeof(List<string>), root);
                ser.Serialize(sw, atusers);
            }
        }
    }
}
